package tools.chapter23;

import java.util.concurrent.*;

/**
 * @author Kevin
 * @date 2020/4/13 19:37
 */
public class FutureTaskDemo {
    //将 FutureTask 对象作为任务提交给 ThreadPoolExecutor 去执行
    public static void demo1() throws ExecutionException, InterruptedException {
        // 创建FutureTask
        FutureTask<Integer> futureTask = new FutureTask<>(() -> 1+2);
        // 创建线程池
        ExecutorService es = Executors.newCachedThreadPool();
        //提交FutureTask
        es.submit(futureTask);
        System.out.println(futureTask.get());
    }
    //将 FutureTask 对象作为任务提交给 Thread 直接执行
    public static void demo2() throws ExecutionException, InterruptedException {
        //创建FutureTask
        FutureTask<Integer> futureTask = new FutureTask<>(() -> 1+2);
        //创建并启动线程
        Thread T1 = new Thread(futureTask);
        T1.start();
        System.out.println(futureTask.get());
    }

    public static void useTeapot() throws ExecutionException, InterruptedException {
        // 创建任务T2的FutureTask
        FutureTask<String> ft2 = new FutureTask<String>(new T2Task());
        // 创建人物T1的FutureTask
        FutureTask<String> ft1 = new FutureTask<String>(new T1Task(ft2));
        //线程1执行任务ft1
        Thread T1 = new Thread(ft1);
        T1.start();
        Thread T2 = new Thread(ft2);
        T2.start();
        //等待线程T1执行结果
        System.out.println(ft1.get());
    }
    // T1Task需要执行的任务:
    // 洗水壶、烧开水、泡茶
    static class T1Task implements Callable<String> {
        FutureTask<String> ft2;

        T1Task(FutureTask<String> ft2) {
            this.ft2 = ft2;
        }

        @Override
        public String call() throws Exception {
            System.out.println("T1:洗水壶...");
            TimeUnit.SECONDS.sleep(1);

            System.out.println("T1:烧开水...");
            TimeUnit.SECONDS.sleep(15);
            //获取T2线程
            String tf = ft2.get();
            System.out.println("T1:拿到茶叶:" + tf);

            return "上茶:" + tf;
        }
    }
    // T2Task需要执行的任务:
    // 洗茶壶、洗茶杯、拿茶叶
    static class T2Task implements Callable<String> {
        @Override
        public String call() throws Exception {
            System.out.println("T2:洗茶壶...");
            TimeUnit.SECONDS.sleep(1);

            System.out.println("T2:洗茶杯...");
            TimeUnit.SECONDS.sleep(2);

            System.out.println("T2:拿茶叶...");
            TimeUnit.SECONDS.sleep(1);
            return "龙井";
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //demo1();
        //demo2();
        useTeapot();
    }
}
